# coding: utf-8

import os
import logging
from logging.handlers import TimedRotatingFileHandler
import datetime
from flask import Flask

from app_config import APP_CONFIG, APP_USER_CONFIG
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)

try:
    os.makedirs(APP_USER_CONFIG['dataDir'])
except:
    pass

APP_CONFIG.SQLALCHEMY_DATABASE_URI = 'sqlite:///{0}/file-sync.db'.format(os.path.abspath(APP_USER_CONFIG['dataDir']))
app.config.from_object(APP_CONFIG)
app.config['SECRET_KEY'] = 'D&WEFSDfsf238493-F+234fASFSASD'

app.db = SQLAlchemy(app)

app.debug = True

log_file_name = 'file-sync.log'
if 'logFileName' in APP_USER_CONFIG:
    log_file_name = APP_USER_CONFIG['logFileName']

date_str = datetime.datetime.now().strftime('%Y-%m-%d-')
log_dir = APP_USER_CONFIG['dataDir'] + '/log/'
try:
    os.makedirs(log_dir)
except:
    pass
log_file_path = log_dir + log_file_name
file_handler = TimedRotatingFileHandler(log_file_path, when='D', interval=7)

file_handler.setFormatter(logging.Formatter(
    '[%(asctime)s][%(levelname)s]%(message)s'
    '[in %(pathname)s:%(lineno)d]'
))

app.logger.addHandler(file_handler)

if 'logLevel' in APP_USER_CONFIG:
    log_level = APP_USER_CONFIG['logLevel']
    if log_level == 'info':
        app.logger.setLevel(logging.INFO)
    elif log_level == 'debug':
        app.logger.setLevel(logging.DEBUG)
    elif log_level == 'warn' or log_level == 'warning':
        app.logger.setLevel(logging.WARN)
    elif log_level == 'error':
        app.logger.setLevel(logging.ERROR)
else:
    app.logger.setLevel(logging.WARN)

# in pycharm we can use app_instance.py as debug entry
if __name__=='__main__':
    app.run(debug=True, host='0.0.0.0', port=8000)







